package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.utils.UserContext;
import com.leyou.user.entity.Address;
import com.leyou.user.mapper.AddressMapper;
import com.leyou.user.service.AddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author BaiZY on 2020/9/12.
 * @version 1.0
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Override
    public boolean addAddress(Address address) {
        address.setUserId(UserContext.getUser().getId());
        boolean flag = save(address);
        return flag;
    }

    @Override
    public List<Address> findAddress() {
        Long useId = UserContext.getUser().getId();
        List<Address> list = query()
                .eq("user_id", useId)
                .list();
        return list;
    }

    @Override
    public boolean deleteAddress(Long userId, Long id) {
        Map<String,Object> map = new HashMap<>();
        map.put("user_id",userId);
        map.put("id",id);
        boolean flag = removeByMap(map);
        return flag;
    }

    @Transactional
    @Override
    public boolean updateDefault(Long userId, Long id) {
        boolean flag = update().eq("user_id", userId)
                .set("is_default", 0)
                .update();

        if (flag){
            flag = update().eq("user_id", userId)
                    .eq("id", id)
                    .set("is_default", 1)
                    .update();
        }

        return flag;
    }

    @Override
    public Address queryAddressById(Long id) {
        Address address = getById(id);
        return address;
    }

    @Override
    public boolean updateAddress(Address address) {
        boolean flag = updateById(address);
        return flag;
    }

    @Override
    public List<Address> findAddressByuserId() {
        List<Address> list = query().eq("user_id", UserContext.getUser().getId()).list();
        return list;
    }
}
